package models

import (
	"gorm.io/gorm"
	"time"
)

// BrokerIncomeSummary 定义了中介收益汇总表的模型
type BrokerIncomeSummary struct {
	gorm.Model
	Month            string  `gorm:"primaryKey; type:varchar(6); not null; index"`   // YYYYMM格式
	Region           string  `gorm:"primaryKey; type:varchar(255); not null; index"` // 省-市格式
	PlaceType        string  `gorm:"primaryKey; type:varchar(50); not null; index"`  // 去处类型
	Transactions     int     `gorm:"type:int; not null"`                             // 达成笔数
	CommissionIncome float64 `gorm:"type:decimal(10,2); not null"`                   // 中介费收入金额
	// 可以根据需要添加其他字段
}

type SummaryResult struct {
	PlaceType             string  `json:"placeType"`
	TotalTransactions     int     `json:"completedRequestsCount"`
	TotalCommissionIncome float64 `json:"brokerageIncome"`
}

type SummaryResultByTime struct {
	Month                 string  `json:"month"`
	Region                string  `json:"region"`
	PlaceType             string  `json:"placeType"`
	TotalTransactions     int     `json:"completedRequestsCount"`
	TotalCommissionIncome float64 `json:"brokerageIncome"`
}

func GetSummary(startMonth, endMonth, region string) ([]SummaryResult, error) {
	var results []SummaryResult

	query := DB.Model(&BrokerIncomeSummary{}).
		Select("place_type, SUM(transactions) as total_transactions, SUM(commission_income) as total_commission_income").
		Where("month >= ? AND month <= ? AND region = ?", startMonth, endMonth, region).
		Group("place_type")

	if err := query.Find(&results).Error; err != nil {
		return nil, err
	}

	return results, nil
}

func GetSummaryByTime(startMonth, endMonth, region string, placeType string) ([]SummaryResultByTime, error) {
	var results []SummaryResultByTime

	query := DB.Model(&BrokerIncomeSummary{}).
		Select("month, region, place_type, transactions as total_transactions, commission_income as total_commission_income").
		Where("month >= ? AND month <= ? AND region = ? AND place_type = ?", startMonth, endMonth, region, placeType)

	if err := query.Find(&results).Error; err != nil {
		return nil, err
	}

	return results, nil
}

func UpdateSummary(tx *gorm.DB, t time.Time, r string, p string, c float64) (*BrokerIncomeSummary, error) {
	// 1. 检查是否存在该月份的记录
	// 2. 如果不存在，创建记录
	// 3. 如果存在，更新记录
	// 4. 返回错误
	// 5. 返回成功

	var b BrokerIncomeSummary
	b.Month = t.Format("200601")
	b.Region = r
	b.PlaceType = p
	err := tx.Where(b).FirstOrCreate(&b).Error

	if err != nil {
		return nil, err
	}

	err = tx.Model(&b).Updates(BrokerIncomeSummary{
		Transactions:     b.Transactions + 1,
		CommissionIncome: b.CommissionIncome + c,
	}).Error

	if err != nil {
		return nil, err
	}
	return &b, nil
}
